package com.iyao.eastat

import android.text.TextWatcher
import android.widget.EditText
import android.text.Editable

/**
 * author : Luck
 * date   : 2021/11/10 14:02
 * desc   :
 */
class AtTextWatcher(private var mListener:AtListener) : TextWatcher {

    var atEndFlag = 8197.toChar()
    private var atIndex = -1
    private var endFlagIndex = -1

    fun insertTextForAt(et: EditText, text: CharSequence?) {
//        var text = text
//        if (atIndex == -1) return
//        val sb = StringBuilder(text)
//        sb.append(atEndFlag)
//        text = sb.toString()
//        val text1 = et.text
//        text1.insert(atIndex + 1, text)
        //        et.invalidate();
    }

    override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
        if (count == 1) { //删除一个字符
            val c = s[start]
            if (c == atEndFlag) {
                endFlagIndex = start
            }
        }
    }

    /**
     * @param s 新文本内容，即文本改变之后的内容
     * @param start 被修改文本的起始偏移量
     * @param before 被替换旧文本长度
     * @param count 替换的新文本长度
     */
    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
        if (count == 1) { //新增(输入)一个字符
            val c = s[start]
            if (c == '@') {
                atIndex = start
                mListener.triggerAt()
            }
        }
        mListener.textChanged(s.toString())
    }

    override fun afterTextChanged(s: Editable) {
        if (endFlagIndex != -1) {
            var index = endFlagIndex
            while (1.let { index -= it; index } != -1) {
                val c = s[index]
                if (c == '@') {
                    break
                }
            }
            val endFlagIndex = endFlagIndex
            this.endFlagIndex = -1
            if (index != -1) s.delete(index, endFlagIndex)
        }
    }

    /**
     * 输入 @ 监听
     */
    interface AtListener {
        fun triggerAt()
        fun textChanged(s: String)
    }
}